﻿
Imports System.Data
Imports VSModel
Imports Cls_Common

Partial Class Control_NopThue_List
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
#Region "Sub and Function"
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "jqueryEnable", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "jqueryEnable", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If
            Bind2Grid()

            btnDelete.Attributes.Add("onclick", "return confirmMultiDelete('" & btnDelete.ClientID & "');")
        End If
    End Sub
    Private Sub Bind2Grid()
        Using Data As New VSEntities
            'set current Huyen
            '  Dim HuyenId As Integer = (From j In Data.UsersProvinces Where j.UserId = _UserId Select j.ProvinceId).ToList
            '  Session("HuyenId") = HuyenId
            ' curHuyenId = HuyenId
            Dim _UserId As Integer = Session("UserId")
            Dim p = (From q In Data.Provinces Join h In Data.UsersProvinces On q.Id Equals h.ProvinceId Where h.UserId = _UserId Select q Order By q.Title).ToList
            With ddlHuyenId
                .DataValueField = "Id"
                .DataTextField = "Title"
                .DataSource = p
                .DataBind()
            End With

        End Using
    End Sub
    Private Sub BindToGrid(Optional ByVal iPage As Integer = 1 _
          , Optional ByVal strMST As String = "" _
          , Optional ByVal strHoTen As String = "" _
          , Optional ByVal strDiaChi As String = "" _
          , Optional ByVal strNganhNghe As String = "" _
          , Optional ByVal strSoGCN As String = "" _
          , Optional ByVal strCMND As String = "" _
          , Optional ByVal strTrangThai As String = "" _
          , Optional ByVal dtmNgayCapFrom As Date = #1/1/1900# _
          , Optional ByVal dtmNgayCapTo As Date = #12/31/3999# _
          , Optional ByVal strSoGCNHo As String = "" _
          , Optional ByVal strCMNDHo As String = "" _
          , Optional ByVal dtmCreatedFrom As Date = #1/1/1900# _
          , Optional ByVal dtmCreatedTo As Date = #12/31/3999# _
          , Optional ByVal strCreator As String = "" _
          , Optional ByVal dtmModifiedFrom As Date = #1/1/1900# _
          , Optional ByVal dtmModifiedTo As Date = #12/31/3999# _
          , Optional ByVal strModifier As String = "" _
          , Optional ByVal strRef1 As String = "" _
          , Optional ByVal strRef2 As String = "" _
          , Optional ByVal intHuyenId As Integer = -1 _
      )
        Using data As New VSEntities
            Dim arrSearch() As String = {iPage, strMST, strHoTen, strDiaChi, strNganhNghe, strSoGCN, strCMND, strTrangThai, dtmNgayCapFrom, dtmNgayCapTo, strSoGCNHo, strCMNDHo, dtmCreatedFrom, dtmCreatedTo, strCreator, dtmModifiedFrom, dtmModifiedTo, strModifier, strRef1, strRef2, intHuyenId}
            ViewState("search") = arrSearch
            'So ban ghi muon the hien tren trang
            Dim intPag_Size As Int32 = drpPage_Size.SelectedValue
            intHuyenId = Session("HuyenId")
            Dim p As List(Of uspNopThueSelectAllList_Result) = data.uspNopThueSelectAllList(strMST _
                , strHoTen _
                , strDiaChi _
                , strNganhNghe _
                , strSoGCN _
                , strCMND _
                , strTrangThai _
                , dtmNgayCapFrom _
                , dtmNgayCapTo _
                , strSoGCNHo _
                , strCMNDHo _
                , dtmCreatedFrom _
                , dtmCreatedTo _
                , strCreator _
                , dtmModifiedFrom _
                , dtmModifiedTo _
                , strModifier _
                , strRef1 _
                , strRef2 _
                , intHuyenId _
            , iPage, intPag_Size).ToList()


            Dim strKey_Name() As String = {"Id", "MST"}
            'Tong so ban ghi
            If p.Count > 0 Then
                hidCount.Value = p(0).Total()
                Create_Pager(hidCount.Value, iPage, intPag_Size, 10)
            Else
                hidCount.Value = 0
                With rptPage
                    .DataSource = Nothing
                    .DataBind()
                End With
            End If
            With grdShow
                .DataKeyNames = strKey_Name
                .DataSource = p
                .DataBind()
            End With
            If (hidCount.Value > 0) Then
                lblTotal.Text = "Hiển thị " + (((iPage - 1) * intPag_Size) + 1).ToString + " đến " + (((iPage - 1) * intPag_Size) + grdShow.Rows.Count).ToString + " trong tổng số " + hidCount.Value.ToString + " bản ghi."
            Else
                lblTotal.Text = ""
            End If
        End Using
    End Sub
    Sub Create_Pager(ByVal Total_Record As Integer, ByVal Page_Index As Integer, ByVal Page_Size As Integer, ByVal Page2Show As Integer)
        Dim TotalPage As Integer = IIf((Total_Record Mod Page_Size) = 0, Total_Record / Page_Size, Total_Record \ Page_Size + 1)
        'lu lai tong so ban ghi
        hidIndex_page.Value = TotalPage
        'gan lai curPage de set active
        hidCur_Page.Value = Page_Index
        'generate ra left page
        Dim cPageGenerate_left As IEnumerable(Of Integer)
        If Page_Index <= Page2Show Then
            cPageGenerate_left = Enumerable.Range(1, Page_Index)
        Else
            cPageGenerate_left = Enumerable.Range(Page_Index - Page2Show, Page2Show)
        End If
        'generate ra right page
        Dim cPageGenerate_Right As IEnumerable(Of Integer)
        If Page_Index + Page2Show <= TotalPage Then
            cPageGenerate_Right = Enumerable.Range(Page_Index, Page2Show + 1)
        Else
            cPageGenerate_Right = Enumerable.Range(Page_Index, TotalPage - Page_Index + 1)
        End If
        'union 2 range va bind to Grid
        With rptPage
            .DataSource = cPageGenerate_left.Union(cPageGenerate_Right)
            .DataBind()
        End With
    End Sub
    Protected Sub rptPage_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptPage.ItemDataBound
        Dim lnkTitle As LinkButton
        lnkTitle = e.Item.FindControl("lnkTitle")
        Dim ScriptManager As System.Web.UI.ScriptManager = System.Web.UI.ScriptManager.GetCurrent(Me.Page)
        ScriptManager.RegisterAsyncPostBackControl(lnkTitle)
        If e.Item.DataItem = hidCur_Page.Value Then
            lnkTitle.Text = "<span class='current'>" & e.Item.DataItem & "</span>"
        Else
            lnkTitle.Text = "<span>" & e.Item.DataItem & "</span>"
        End If
        lnkTitle.ToolTip = e.Item.DataItem
    End Sub
    Protected Sub lnkTitle_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lnkTile As LinkButton = CType(sender, LinkButton)
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(CInt(lnkTile.ToolTip) _
       , arrSearch(1) _
       , arrSearch(2) _
       , arrSearch(3) _
       , arrSearch(4) _
       , arrSearch(5) _
       , arrSearch(6) _
       , arrSearch(7) _
       , arrSearch(8) _
       , arrSearch(9) _
       , arrSearch(10) _
       , arrSearch(11) _
       , arrSearch(12) _
       , arrSearch(13) _
       , arrSearch(14) _
       , arrSearch(15) _
       , arrSearch(16) _
       , arrSearch(17) _
        )
        lnkLast.Enabled = True
        lnkFirst.Enabled = True
        If CInt(lnkTile.ToolTip) = hidIndex_page.Value Then
            lnkLast.Enabled = False
        ElseIf CInt(lnkTile.ToolTip) = 1 Then
            lnkFirst.Enabled = False
        End If
    End Sub
    Protected Sub lnkFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkFirst.Click
        If hidCur_Page.Value > 1 Then
            hidCur_Page.Value = hidCur_Page.Value - 1
        End If
        BindToGrid(hidCur_Page.Value)
    End Sub
    Protected Sub lnkLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkLast.Click
        hidCur_Page.Value = hidCur_Page.Value + 1
        BindToGrid(hidCur_Page.Value)
    End Sub
#End Region
#Region "Event for control"
    Protected Sub lnkbtnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim intId As Integer
        Dim strLogName As String = ""
        Using data As New VSEntities
            intId = grdShow.DataKeys(hidID.Value)("Id").ToString
            Dim q = (From p In data.NopThues Where p.Id = intId Select p).FirstOrDefault
            Try
                data.NopThues.DeleteObject(q)
                data.SaveChanges()
                'Insert_App_Log("Insert  NopThue:" & txtTitle.Text.Trim & "", Function_Name.NopThue, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                Excute_Javascript("Alertbox('Xóa dữ liệu thành công.');", Me.Page, True)
            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
            End Try
        End Using
        BindToGrid()
    End Sub
    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim intId As Integer = 0
        Dim intCount As Integer
        Dim intTotal As Integer
        Using data As New VSEntities
            Try
                For Each item As GridViewRow In grdShow.Rows
                    Dim chkItem As New CheckBox
                    chkItem = CType(item.FindControl("chkItem"), CheckBox)
                    If chkItem.Checked Then
                        intTotal += 1
                        intId = grdShow.DataKeys(item.RowIndex)("Id").ToString
                        Dim q = (From p In data.NopThues Where p.Id = intId Select p).FirstOrDefault
                        Try
                            data.NopThues.DeleteObject(q)
                            'Insert_App_Log("Insert  NopThue:" & txtTitle.Text.Trim & "", Function_Name.NopThue, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                            data.SaveChanges()
                            intCount += 1
                        Catch ex As Exception
                        End Try
                    End If
                Next
                If intCount > 0 Then
                    Excute_Javascript("Alertbox('Xóa dữ liệu thành công. " & intCount.ToString & " /" & intTotal.ToString & " record.');", Me.Page, True)
                Else
                    Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
                End If
            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
            End Try
        End Using
        BindToGrid()
    End Sub
    Protected Sub grdShow_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdShow.RowDataBound
        If e.Row.RowIndex >= 0 Then
            Dim lblSTT As Label = CType(e.Row.FindControl("lblSTT"), Label)
            lblSTT.Text = CInt(drpPage_Size.SelectedValue) * (CInt(hidCur_Page.Value) - 1).ToString + e.Row.RowIndex + 1
            Dim lnkbtnDelete As LinkButton = CType(e.Row.FindControl("lnkbtnDelete"), LinkButton)
            lnkbtnDelete.Attributes.Add("onclick", "return ComfirmDialog('" + drpMessage.Items(0).Text + "', 0,'" + lnkbtnDelete.ClientID + "','" + e.Row.RowIndex.ToString + "',1);")
            'Dim hplEdit As HyperLink = CType(e.Row.FindControl("hplEdit"), HyperLink)
            'hplEdit.NavigateUrl = "../../Page/NopThue/Edit.aspx?Id=" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString
            'Dim hplMst As HyperLink = CType(e.Row.FindControl("hplMst"), HyperLink)
            'hplMst.NavigateUrl = "../../Page/NopThue/Detail.aspx?Id=" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString
            'hplMst.Text = grdShow.DataKeys(e.Row.RowIndex)("MST").ToString
        End If
    End Sub
#End Region
#Region "Search"
    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        BindToGrid(1 _
             , txtMst.Text.Trim _
            , txtHoten.Text.Trim _
            , txtDiachi.Text.Trim _
            , txtNganhnghe.Text.Trim _
            , txtSogcn.Text.Trim _
            , txtCmnd.Text.Trim _
            , txtTrangthai.Text.Trim _
            , StringToDate(txtNgaycapFrom.Text.Trim, "dd/mm/yyyy") _
            , StringToDate(IIf(String.IsNullOrEmpty(txtNgaycapTo.Text.Trim) = True, "31/12/3999", txtNgaycapTo.Text.Trim), "dd/mm/yyyy")
            )
    End Sub
    Protected Sub drpPage_Size_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drpPage_Size.SelectedIndexChanged
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(1 _
          , arrSearch(1) _
           , arrSearch(2) _
           , arrSearch(3) _
           , arrSearch(4) _
           , arrSearch(5) _
           , arrSearch(6) _
           , arrSearch(7) _
           , arrSearch(8) _
           , arrSearch(9) _
           , arrSearch(10) _
           , arrSearch(11) _
           , arrSearch(12) _
           , arrSearch(13) _
           , arrSearch(14) _
           , arrSearch(15) _
           , arrSearch(16) _
           , arrSearch(17) _
         )
    End Sub
    Protected Sub btnReset_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReset.Click

        txtMst.Text = ""
        txtHoten.Text = ""
        txtDiachi.Text = ""
        txtNganhnghe.Text = ""
        txtSogcn.Text = ""
        txtCmnd.Text = ""
        txtTrangthai.Text = ""
        txtNgaycapFrom.Text = ""
        txtNgaycapTo.Text = ""
        drpPage_Size.SelectedIndex = -1
        ddlHuyenId.SelectedIndex = -1
        BindToGrid(1)
    End Sub
#End Region
End Class
